package com.loma.websocket;

import com.loma.entity.Msg;
import com.loma.utils.JsonUtil;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@ServerEndpoint(value = "/socketServer/{userid}")
@Component
public class SocketServer {

    private static Session session;
    private static Map<String, Session> sessionPool = new HashMap<String, Session>();
    private static Map<String, String> sessionIds = new HashMap<String, String>();

    /**
     * 用户连接时触发
     *
     * @param session
     * @param userid
     */
    @OnOpen
    public void open(Session session, @PathParam(value = "userid") String userid) {
        this.session = session;

        sessionPool.put(userid, session);
        sessionIds.put(session.getId(), userid);
        online(userid);
    }

    /**
     * 收到信息时触发
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {

        System.out.println("当前发送人sessionid为" + sessionIds.get(session.getId()) + "发送内容为" + message);


        sendAll(message);
    }

    /**
     * 连接关闭触发
     */
    @OnClose
    public void onClose() {
        sessionPool.remove(sessionIds.get(session.getId()));
        sessionIds.remove(session.getId());
    }

    /**
     * 发生错误时触发
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 信息发送的方法
     *
     * @param message
     */
    public static void sendMessage(String message) {

        Msg msg = JsonUtil.fromJson(message, Msg.class);
        Session s = sessionPool.get(msg.getToUser());
        Date date = new Date();
        msg.setDate(date);
        sessionIds.get(session.getId());
        msg.setFromUser(sessionIds.get(session.getId()));

        if (s != null) {

            try {
                s.getBasicRemote().sendText(JsonUtil.toJson(msg));

                System.out.println(JsonUtil.toJson(msg));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    /**
     * 获取当前连接数
     *
     * @return
     */
    public int getOnlineNum() {
        return sessionPool.size();
    }

    /**
     * 获取在线用户名以逗号隔开
     *
     * @return
     */
    public static String getOnlineUsers() {
        StringBuffer users = new StringBuffer();
        for (String key : sessionIds.keySet()) {
            users.append(sessionIds.get(key) + ",");
        }
        return users.toString();
    }

    /**
     * 信息群发
     *
     * @param message
     */
    public static void sendAll(String message) {
        Date date = new Date();
        Msg msg = JsonUtil.fromJson(message, Msg.class);

        msg.setDate(date);
        msg.setFromUser(sessionIds.get(session.getId()));
        for (String key : sessionIds.keySet()) {
            msg.setToUser(key);
            String toUserId = sessionIds.get(key);
            Session s = sessionPool.get(toUserId);
            if (s != null) {
                try {
                    s.getBasicRemote().sendText(JsonUtil.toJson(msg));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                //写入未读消息数据库,等下次上线现发送
            }

        }
    }


    /**
     * 信息群发
     *
     */
    public static void sendAll(Msg msg) {
        Date date = new Date();

        msg.setDate(date);
        msg.setFromUser(sessionIds.get(session.getId()));
        for (String key : sessionIds.keySet()) {
            msg.setToUser(key);
            String toUserId = sessionIds.get(key);
            Session s = sessionPool.get(toUserId);
            if (s != null) {
                try {
                    s.getBasicRemote().sendText(JsonUtil.toJson(msg));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                //写入未读消息数据库,等下次上线现发送
            }

        }
    }


    /**
     * 上线通知
     *
     */
    public   void online(String userId) {
        Msg msg=new Msg();
        msg.setCmd(CMD.online);
        msg.setFromUser("System");
        msg.setDate(new Date());
        msg.setText(userId + "上线了");
        System.out.println(userId + "上线了");


        for (String key : sessionPool.keySet()) {


            Session s = sessionPool.get(key);
            if (s != null) {
                try {
                    s.getBasicRemote().sendText(JsonUtil.toJson(msg));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
